// 系统日志模块hooks

import { useState, useCallback } from 'react';
import {
  getSysLogs,
  getSysLogDetail,
} from '../api';
import {
  SysLog,
  SysLogListResponse,
  SysLogQueryParams,
} from '../types';

export const useLog = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取系统日志列表
  const fetchSysLogs = useCallback(async (params: SysLogQueryParams = {}) => {
    setLoading(true);
    setError(null);
    try {
      const response = await getSysLogs(params);
      if (response.code === 200) {
        return response.data as SysLogListResponse;
      } else {
        throw new Error(response.message || '获取系统日志失败');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取系统日志失败';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取系统日志详情
  const fetchSysLogDetail = useCallback(async (logId: number) => {
    setLoading(true);
    setError(null);
    try {
      const response = await getSysLogDetail(logId);
      if (response.code === 200) {
        return response.data as SysLog;
      } else {
        throw new Error(response.message || '获取系统日志详情失败');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取系统日志详情失败';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  // 清除错误
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    loading,
    error,
    clearError,
    fetchSysLogs,
    fetchSysLogDetail,
  };
}; 